package com.sync.syncmasterdata.customer.service.http;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 云枢api服务类
 */
@Service
@Slf4j
@ConfigurationProperties(prefix = "cloudpivotprops")
@Data
public class CPAPIService {
    @Autowired
    private HttpAPIServiceForCrmSync httpAPIServiceForCrmSync;

    @Value("${cloudpivotprops.url}")
    private  String URL;

    @Value("${cloudpivotprops.client_secret}")
    private  String CLIENT_SECRET;

    @Value("${cloudpivotprops.client_id}")
    private  String CLIENT_ID;

    @Value("${cloudpivotprops.redirect_uri}")
    private  String REDIRECT_URI;

    @Value("${cloudpivotprops.username}")
    private  String USERNAME;

    @Value("${cloudpivotprops.password}")
    private  String PASSWORD;

    @Value("${cloudpivotprops.urlkey}")
    private  String URLKEY;
    
    @Value("${cloudpivotprops.corpId}")
    private  String CORPID;

    /**
     * 获取token
     */
    public String getToken() throws Exception {
        String key = getKey();
        String path = String.format("%s%s", URL, "/login/Authentication/get_token?");
        Map<String,String>  requestMap= new HashMap<>();
        JSONObject responseJson = null;
        requestMap.put("code", key);
        requestMap.put("client_secret", CLIENT_SECRET);
        requestMap.put("url", URL);
        requestMap.put("client_id", CLIENT_ID);
        requestMap.put("redirect_uri", REDIRECT_URI);

        responseJson = new JSONObject(httpAPIServiceForCrmSync.doGet(path,requestMap));
        String access_token = responseJson.getString("access_token");
//        log.info("返回token:" + access_token);
        return access_token;
    }

    /**
     * 获取key
     * @return
     */
    private String getKey() throws Exception {
        //请求地址
        String path = String.format("%s%s",URL,"/login/Authentication/get_code");
        JSONObject requestJson = new JSONObject();
        JSONObject responseJson = null;
        requestJson.put("username", USERNAME);
        requestJson.put("password", PASSWORD);
        requestJson.put("url", URLKEY);
        requestJson.put("corpId", CORPID);

        String responseStr=this.httpAPIServiceForCrmSync.doPost(path, requestJson.toString());
        responseJson=new JSONObject(responseStr);
        log.info("返回json-key:" + responseJson.getString("code"));
        String reKey=null;
        reKey = responseJson.getString("code");
        if (reKey != null) {
            return reKey;
        }
        return null;
    }
}
